<template>
    <div>

        <el-row :gutter="10">
            <el-col :span="5">

                <el-menu
                        :default-active="$route.path"
                        class="el-menu-vertical-demo"
                        @open="handleOpen"
                        @close="handleClose"
                        @select="handleSelect" :router="true"
                >

                    <el-menu-item index="/personalCenter">
                        <i class="el-icon-s-tools"></i>
                        <span slot="title">个人中心</span>
                    </el-menu-item>

                    <el-menu-item index="/myFavorites">
                        <i class="el-icon-star-on"></i>
                        <span slot="title">我的收藏</span>
                    </el-menu-item>

                </el-menu>

            </el-col>


            <el-col :span="19">
                <el-card style="height: 350px;">
                    <el-col :span="19">
                        <el-descriptions class="margin-top" title="个人信息" :column="2" size="medium" border>
                            <template slot="extra">
                                <el-button type="primary" size="small" @click="showEdit">修改信息</el-button>

                                <el-dialog title="修改个人信息" :visible.sync="dialogFormVisible_edit">
                                    <el-form :model="edit_user" :rules="userRules" ref="editUserRef">

                                        <el-form-item prop="name" label="昵称" label-width="100px">
                                            <el-input v-model="edit_user.name" autocomplete="off"
                                                      placeholder="请输入昵称"></el-input>
                                        </el-form-item>

                                        <el-form-item prop="sex" label="性别" label-width="100px">
                                            <!--                                            <el-input v-model="edit_user.sex" autocomplete="off"-->
                                            <!--                                                      placeholder="请输入性别"></el-input>-->
                                            <el-select style="width: 210px" v-model="edit_user.sex" placeholder="请选择"
                                                       clearable>
                                                <el-option
                                                        v-for="item in sexs"
                                                        :key="item.value"
                                                        :label="item.label"
                                                        :value="item.value">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>

                                        <el-form-item prop="phone" label="手机号" label-width="100px">
                                            <el-input v-model="edit_user.phone" autocomplete="off"
                                                      placeholder="请输入手机号"></el-input>
                                        </el-form-item>

                                        <el-form-item prop="email" label="电子邮箱" label-width="100px">
                                            <el-input v-model="edit_user.email" autocomplete="off"
                                                      placeholder="请输入电子邮箱"></el-input>
                                        </el-form-item>

                                        <el-form-item prop="address" label="地址" label-width="100px">
                                            <el-input v-model="edit_user.address" autocomplete="off"
                                                      placeholder="请输入地址"></el-input>
                                        </el-form-item>


                                        <el-form-item prop="avatar" label="头像" label-width="100px">
                                            <div style="display: flex;align-items: center;flex-direction: row;margin: 20px">
                                                <el-avatar shape="square"
                                                           :size="100"
                                                           fit="fill"
                                                           :src="edit_user.avatar"
                                                           style="margin-left: 50px"
                                                ></el-avatar>
                                                <el-upload
                                                        :show-file-list="false"
                                                        :action="$baseUrl + '/file/upload'"
                                                        :on-success="handleFileUpload"
                                                        style="margin-left: 50px"
                                                >
                                                    <el-button type="primary">上传头像</el-button>
                                                </el-upload>

                                            </div>

                                        </el-form-item>

                                    </el-form>


                                    <div slot="footer" class="dialog-footer">
                                        <el-button @click="cancelDialog_editUser">取 消</el-button>
                                        <el-button type="primary" @click="handleEdit">确 定</el-button>
                                    </div>

                                </el-dialog>
                            </template>

                            <el-descriptions-item>
                                <template slot="label">
                                    <i class="el-icon-user"></i>
                                    头像
                                </template>
                                <el-avatar shape="square" :size="80" fit="fill" :src="account.avatar"></el-avatar>
                            </el-descriptions-item>

                            <el-descriptions-item>
                                <template slot="label">
                                    <i class="el-icon-user-solid"></i>
                                    用户名
                                </template>
                                {{ account.name }}
                            </el-descriptions-item>

                            <el-descriptions-item>
                                <template slot="label">
                                    <i class="el-icon-user"></i>
                                    账号
                                </template>
                                {{ account.username }}
                            </el-descriptions-item>


                            <el-descriptions-item>
                                <template slot="label">
                                    <i class="el-icon-mobile-phone"></i>
                                    手机号
                                </template>
                                {{ account.phone }}
                            </el-descriptions-item>

                            <el-descriptions-item>
                                <template slot="label">
                                    <i class="el-icon-discover"></i>
                                    性别
                                </template>
                                {{ account.sex }}
                            </el-descriptions-item>

                            <el-descriptions-item>
                                <template slot="label">
                                    <i class="el-icon-chat-line-round"></i>
                                    邮箱
                                </template>
                                {{ account.email }}
                            </el-descriptions-item>

                            <el-descriptions-item>
                                <template slot="label">
                                    <i class="el-icon-office-building"></i>
                                    联系地址
                                </template>
                                {{ account.address }}
                            </el-descriptions-item>

                        </el-descriptions>
                    </el-col>
                </el-card>

                <el-card>
                    <div slot="header" class="clearfix">
                        <span style="font-size: 15px;font-weight: bold">修改密码</span>
                    </div>

                    <el-form :rules="passRules" ref="changePasswordRef" style="margin-left: 50px">

                        <el-form-item prop="password">
                            <el-input style="width: 400px" prefix-icon="el-icon-lock" show-password clearable
                                      v-model="password" placeholder="请输入现在使用的密码"></el-input>
                        </el-form-item>


                        <el-form-item prop="newPassword">
                            <el-input style="width: 400px" prefix-icon="el-icon-lock" show-password clearable
                                      v-model="newPassword" placeholder="请输入新密码"></el-input>
                        </el-form-item>


                        <el-form-item prop="confirmPassword">
                            <el-input style="width: 400px" prefix-icon="el-icon-lock" show-password clearable
                                      v-model="confirmPassword" placeholder="请再次输入新密码"></el-input>
                        </el-form-item>

                        <el-form-item prop="code">
                            <div style="display: flex;justify-content: center;align-items: center">
                                <el-input prefix-icon="el-icon-place" clearable v-model="code"
                                          placeholder="请输入验证码" style="width: 280px"></el-input>
                                <div style="flex: 1;margin-left: 30px">
                                    <valid-code @update:value="getCode"
                                                style="height: 36px;width: 80px"></valid-code>
                                </div>
                            </div>
                        </el-form-item>

                        <el-form-item>
                            <el-button style="margin: 50px 40px 0 30px;width: 150px" type="primary"
                                       @click="changePassword"> 修 改 密 码
                            </el-button>
                            <el-button style="width: 150px" @click="reset('changePasswordRef')"> 重 置
                            </el-button>
                        </el-form-item>

                    </el-form>

                </el-card>

            </el-col>

        </el-row>

    </div>
</template>
<script>
import {defineComponent} from 'vue'
import ValidCode from "@/conponents/ValidCode.vue";
import crypto from "@/utils/encryp";


export default defineComponent({
    name: "PersonalCenter",
    components: {ValidCode},
    data() {

        // 自定义校验规则
        const validateCode = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入验证码'))
            } else if (this.code.toLowerCase() !== this.confirmCode) {
                callback(new Error('验证码错误'))
            } else {
                callback()
            }
        };

        // 确认密码校验
        const validatePassword = (rule, confirmPassword, callback) => {
            console.log(this.confirmPassword)
            if (this.confirmPassword === '') {
                callback(new Error('请确认密码'))
            } else if (this.confirmPassword !== this.newPassword) {
                callback(new Error('两次输入的密码不一致'))
            } else {
                callback()
            }
        };

        // 手机号验证
        const validatePhone = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入手机号"));
            } else {
                if (!/^1[3456789]\d{9}$/.test(value)) {
                    callback(new Error("请输入正确的手机号"));
                } else {
                    callback();
                }
            }
        };


        return {
            dialogFormVisible_edit: false,     // 编辑按钮弹出框
            activeIndex: '/personalCenter',
            userId: '',
            confirmPassword: '',
            password: '',
            newPassword: '',
            code: '',
            confirmCode: '',

            account: {},
            edit_user: {},
            edit_user_temp: {},
            sexs: [{             // 存储所有状态
                value: '男',
                label: '男'
            }, {
                value: '女',
                label: '女'
            }],

            passRules: {
                confirmPassword: [
                    {validator: validatePassword, trigger: 'blur'}
                ],
                code: [
                    {validator: validateCode, trigger: 'blur'}
                ]
            },

            userRules: {
                name: [
                    {required: true, message: '请输入昵称', trigger: 'blur'}
                ],
                phone: [
                    {required: true, validator: validatePhone, message: '请输入正确手机号', trigger: "change"}
                ],
                email: [
                    {required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: 'change'}
                ],
                sex: [
                    {required: true, message: '请输入性别', trigger: 'blur'}
                ],
                address: [
                    {required: true, message: '请输入地址', trigger: 'blur'}
                ],
                // avatarUrl: [
                //     {required: true, message: '请上传头像', trigger: 'blur'}
                // ],
                avatar: [
                    {required: true, message: '请上传头像', trigger: 'blur'}
                ]
            }


        }
    },
    mounted() {
        // 获取用户ID
        this.account = JSON.parse(localStorage.getItem('account'))
        this.userId = this.account.id
    },
    methods: {

        // 重置按钮
        reset(formName) {
            this.clearcheck(formName)
            this.password = ''
            this.newPassword = ''
        },


        // 移除表单的校验
        clearcheck(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].clearValidate()
            }
        },

        // 获取验证码
        getCode(code) {
            this.confirmCode = code.toLowerCase();
        },


        handleEdit() {
            // 更新用户头像信息
            // this.edit_user.avatar = this.avatarUrl
            // 密码处理
            // if (this.edit_user.password !== ''
            //     && this.edit_user.password !== undefined
            //     && this.edit_user.password !== null) {
            //     // 加密密码处理
            //     let pwd = this.edit_user.password.toString()
            //     pwd = this.$md5(pwd)
            //     this.edit_user.password = pwd
            // } else {
            //     this.edit_user.password = this.edit_user_temp.password
            // }
            // 状态转化
            // for (let i = 0; i < this.statuss.length; i++) {
            //     if (this.edit_user.status === this.statuss[i].label) {
            //         this.edit_user.status = this.statuss[i].value
            //         break
            //     }
            // }

            this.dialogFormVisible_edit = false;

            // 输入检验
            this.$refs['editUserRef'].validate((valid) => {
                if (valid) {
                    // 校验通过
                    this.$request.post('/user/updateSimpleById', this.edit_user).then(res => {
                        // console.log(res)
                        if (res.code === '200') {
                            this.$message.success('修改成功');
                            localStorage.setItem('account', JSON.stringify(this.edit_user))
                            this.account = this.edit_user
                            this.edit_user = {}
                            // 更新本地的用户信息
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                } else {
                    this.$message.error('请输入完整信息')
                }
            })
        },

        // 处理 头像上传按钮   的点击事件
        handleFileUpload(response, file, fileList) {
            console.log(file)

            // 判断上传的文件的类型
            // 只能上传图片类型，如果不是图片资源那么提示“只能上传图片！！”
            if (!file.raw.type.includes('image')) {
                this.$message.error('只能上传图片！')
                return
            }

            if (response.data) {
                // 数据解密
                let key = "dianzishumaMall0"; //加密密钥
                let iv = "dianzishumaMall0"; //加密aesIV，偏移量

                const data = crypto.decryptAES(response.data, key, iv)
                response.data = JSON.parse(data)
            }


            //  1. 获取上传成功后返回的图片地址

            let url = response.data;
            // 2. 修改表单中对应的字段值
            this.avatarUrl = url;
            this.edit_user.avatar = url
            // 刷新头像信息
            this.$forceUpdate()

        },

        // 取消修改信息
        cancelDialog_editUser() {
            this.dialogFormVisible_edit = false;
            this.edit_user = {}
            // this.avatarUrl = ''
        },

        showEdit() {

            // 将当前行的用户数据传入form中
            this.edit_user = JSON.parse(JSON.stringify(this.account))
            this.edit_user_temp = JSON.parse(JSON.stringify(this.account))
            // 更新当前头像
            // this.avatarUrl = JSON.parse(JSON.stringify(this.account.avatar))

            this.clearcheck('editUserRef')
            // 显示弹窗
            this.dialogFormVisible_edit = true;

        },

        handleOpen(key, keyPath) {
            console.log(key, keyPath);
        },
        handleClose(key, keyPath) {
            console.log(key, keyPath);
        },
        handleSelect(key, keyPath) {
            // console.log(key, keyPath);
            this.$router.push(key)
            this.activeIndex = key
        },


        changePassword() {
            if (this.confirmCode !== this.code) {
                this.$message.error('验证码错误')
                this.code = ''
                return
            }
            if (this.password === ''
                || this.password === undefined
                || this.password === null
                || this.confirmPassword === ''
                || this.confirmPassword === undefined
                || this.confirmPassword === null) {
                this.$message.error('密码不能为空')
                return
            } else {
                let pwd = this.password.toString()
                pwd = this.$md5(pwd)
                this.password = pwd
                pwd = this.newPassword.toString()
                pwd = this.$md5(pwd)
                this.newPassword = pwd
                pwd = this.confirmPassword.toString()
                pwd = this.$md5(pwd)
                this.confirmPassword = pwd
            }

            // 密码处理
            if (this.newPassword !== this.confirmPassword) {
                this.$message.error('两次输入的密码不一致')
                return
            }
            if (this.password !== ''
                && this.password !== undefined
                && this.password !== null) {
            } else {
                this.$message.info('密码未修改')
                return;
            }


            // 校验通过，发送请求
            this.$request.post('/user/changePasswordById' + '?id=' + this.userId + '&password=' + this.password + '&newPassword=' + this.newPassword).then(res => {
                if (res.code === '200') {
                    this.$message.success('修改成功');
                    // 清空存储的用户信息
                    this.logout()
                } else {
                    this.$message.error(res.msg);
                }
            })


        },

        // 退出登录
        logout() {
            // 清除用户数据
            localStorage.removeItem("account");

            // 提示用户退出登录
            this.$message.success("退出登录成功！")

            // 跳转到登录页面
            this.$router.push("/login")
        },

    }
})
</script>


<style scoped>

</style>